package com.aibaixun.common.utils;

import com.aibaixun.common.constant.ApiConstants;
import com.aibaixun.common.constant.CacheConstants;
import com.aibaixun.common.utils.redis.RedisUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;

/**
 * 获取第三方调用token
 */
@Slf4j
public class OpenApiTokenUtils {
    /**
     * 获取第三方公共调用token
     */
    public String getTokenForGa() {
        BufferedReader bufferedReader = null;
        try {
            Object value = RedisUtils.getCacheObject(CacheConstants.OPEN_API_TOKEN+"gs001");
            if (value != null){
                return value.toString();
            }
            URL url = new URL(ApiConstants.IP_ADDRESS+"/api/blade-auth/oauth/token?username=share_baixun&password=5cad051b559cddd3be794bb2597fd2a6&grant_type=password");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization","Basic c2FiZXI6c2FiZXJfc2VjcmV0");
            conn.setRequestProperty("Tenant-Id","000000");
            InputStream inputStream = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(isr);
            String str;
            StringBuilder builder = new StringBuilder();
            while ((str = bufferedReader.readLine()) != null) {
                builder.append(str);
            }
            conn.disconnect();
            JSONObject jsonObject = JSONObject.parseObject(builder.toString());
            String token = jsonObject.getString("token_type")+" "+jsonObject.getString("access_token");
            RedisUtils.setCacheObject(CacheConstants.OPEN_API_TOKEN+"gs001", token, Duration.ofHours(2));
            return token;
        } catch (Exception e) {
            return e.getMessage();
        } finally {
            // 释放资源
            try {
                if(null != bufferedReader) {
                    bufferedReader.close();
                }
            } catch (IOException e) {

            }
        }
    }
}
